package org.grizz.game.entities;

import java.util.ArrayList;
import java.util.List;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;

public class CircularEntity implements Entity {
	private ShapeRenderer renderer;
	private Rectangle area;
	
	private List<MovingPoint> points;
	private Color color;

	
	public CircularEntity(ShapeRenderer renderer, Rectangle area, int vertices) {
		this.renderer = renderer;
		this.area = area;
		
		points = new ArrayList<MovingPoint>();
		color = new Color();
		
		createVertices(vertices);
	}
	
	private void createVertices(int vertices) {
		double radianOffset = Math.toRadians(360d / vertices);
		int screenOffsetX = (int) area.x;
		int screenOffsetY = (int) area.y;
		int screenWidth = (int) area.width;
		int screenHeight = (int) area.height;
		
		for (int i = 0; i < vertices; i++) {
			float x = MathUtils.sin((float) (radianOffset * i)) * (screenWidth / 4) + (screenWidth / 2) + screenOffsetX;
			float y = MathUtils.cos((float) (radianOffset * i)) * (screenHeight / 4) + (screenHeight / 2) + screenOffsetY;
			
			float dx = MathUtils.sin((float) (radianOffset * i));
			float dy = MathUtils.cos((float) (radianOffset * i));
			
			MovingPoint point = new MovingPoint()
				.setLocation(new Vector2(x, y))
				.setSpeed(new Vector2(dx, dy));
			
			points.add(point);
		}
	}

	public void setColor(Color color) {
		this.color.set(color);
	}
	
	@Override
	public void update(float delta) {
		for (MovingPoint point : points) {
			point.bounceInside(area);
			point.move(delta * 50);
		}
	}
	
	@Override
	public void draw() {
		renderer.setColor(color);
		renderer.begin(ShapeType.Line);
		
		MovingPoint lastPoint = points.get(points.size() - 1);
		
		for (MovingPoint point : points) {
			renderer.line(lastPoint.getLocation(), point.getLocation());
			
			lastPoint = point;
		}
		
		renderer.end();
	}
}
